import React, { ReactElement, useState } from 'react'
import { Modal, Button, Input, Rate, Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { addItem } from '@/api/item'
import { connect } from 'umi'
import styles from '../../index.less'

interface Props {
    init: Function,
    dialog: boolean,
    changeFlag: Function
}

function getBase64(img: any, callback: any) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

// 上传之前
function beforeUpload(file: any) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

function Dialog({ init, dialog, changeFlag }: Props): ReactElement {
    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState("")
    const [equipInfo, setEquipInfo] = useState({
        desc: "",
        detail: "",
        icon: "",
        name: "",
        star: 0
    })
    function handleChange(info: any) {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            const equipInfo2 = JSON.parse(JSON.stringify(equipInfo))
            equipInfo2.icon = info.file.response.url
            setEquipInfo(equipInfo2)
            getBase64(info.file.originFileObj, (imageUrl: string) => {
                setImageUrl(imageUrl)
                setLoading(false)
            });
        }
    };

    const showModal = () => {
        changeFlag(true);
    };

    const handleOk = () => {
        console.log(equipInfo)
        addItem(equipInfo).then(res => {
            changeFlag(false)
            init()
        })
        
    };

    const handleCancel = () => {
        changeFlag(false);
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <div>
            <Button type="primary" onClick={showModal}>
                + 添加装备
            </Button>
            <Modal
                title="添加装备"
                visible={dialog}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                <ul className={styles.oul}>
                    <li>
                        <span>
                            物品名称
                        </span>
                        <div>
                            <Input value={ equipInfo.name } onChange={(ev) => {
                                const equipInfo2 = JSON.parse(JSON.stringify(equipInfo))
                                equipInfo2.name = ev.target.value
                                setEquipInfo(equipInfo2)
                            }} />
                        </div>
                    </li>
                    <li>
                        <span>
                            物品图标
                        </span>
                        <div>
                            <Upload
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="/api/admin/api/upload/item"
                                headers={{
                                    Authorization: sessionStorage.getItem('token')
                                }}
                                beforeUpload={beforeUpload}
                                onChange={handleChange}
                            >

                                {imageUrl ? <img style={{
                                    width: 100,
                                    height: 100
                                }} src={imageUrl}></img> : uploadButton}
                            </Upload>
                        </div>
                    </li>
                    <li>
                        <span>
                            星级
                        </span>
                        <div>
                            <Rate value={equipInfo.star} onChange={(value) => {
                                 const equipInfo2 = JSON.parse(JSON.stringify(equipInfo))
                                 equipInfo2.star = value
                                 setEquipInfo(equipInfo2)
                            }} count={3} />
                        </div>
                    </li>
                    <li>
                        <span>
                            物品简介
                        </span>
                        <div>
                            <Input value={ equipInfo.desc } onChange={(ev) => {
                                const equipInfo2 = JSON.parse(JSON.stringify(equipInfo))
                                equipInfo2.desc = ev.target.value
                                setEquipInfo(equipInfo2)
                            }}  />
                        </div>
                    </li>
                    <li>
                        <span>
                            物品详情
                        </span>
                        <div>
                            <Input value={ equipInfo.detail } onChange={(ev) => {
                                const equipInfo2 = JSON.parse(JSON.stringify(equipInfo))
                                equipInfo2.detail = ev.target.value
                                setEquipInfo(equipInfo2)
                            }}  />
                        </div>
                    </li>
                </ul>
            </Modal>
        </div>
    )
}

export default connect((state: any) => {
    const { dialog } = state
    return {
        dialog
    }
}, (dispatch) => {
    return {
        changeFlag(flag: boolean) {
            dispatch({ type: "dialog/changeFlag", flag })
        }
    }
})(Dialog)
